package zgrjb.snbq.teach_platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.events.Event;
import zgrjb.snbq.teach_platform.dto.model.CommentDO;
import zgrjb.snbq.teach_platform.dto.model.TopicDO;
import zgrjb.snbq.teach_platform.dto.model.User;
import zgrjb.snbq.teach_platform.dto.req.AddTopicRequest;
import zgrjb.snbq.teach_platform.dto.req.QueryTopicRequest;
import zgrjb.snbq.teach_platform.interceptor.LoginInterceptor;
import zgrjb.snbq.teach_platform.mapper.TopicMapper;
import zgrjb.snbq.teach_platform.service.TopicService;
import zgrjb.snbq.teach_platform.util.IDUtil;
import zgrjb.snbq.teach_platform.util.JsonData;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TopicServiceImpl implements TopicService {

    @Autowired
    private TopicMapper topicMapper;

    @Override
    public JsonData add(AddTopicRequest request) {
        User user = LoginInterceptor.getCurrentUser();
        TopicDO topicDO = new TopicDO();
        topicDO.setId((Long) IDUtil.geneSnowFlakeID());
        topicDO.setClassId(request.getClassId());
        topicDO.setStudentId(user.getId());
        topicDO.setAuthor(user.getName());
        topicDO.setMainInfo(request.getMainInfo());
        topicMapper.insert(topicDO);
        return JsonData.buildSuccess();
    }

    @Override
    public JsonData list(QueryTopicRequest request) {
        Integer size = request.getSize();
        Integer page = request.getPage();
        User loginUser = LoginInterceptor.getCurrentUser();

        Page<TopicDO> topicPage = new Page<>(page, size);
        Page<TopicDO> topicPageRes = topicMapper.selectPage(topicPage, new QueryWrapper<TopicDO>()
                .eq("class_id", request.getClassId())
                .orderByDesc("create_time"));

        return JsonData.buildSuccess(topicPageRes);
    }

    @Override
    public JsonData del(Long topicId) {
        User user = LoginInterceptor.getCurrentUser();
        int row = topicMapper.delete(new QueryWrapper<TopicDO>()
                .eq("id", topicId)
                .eq("student_id", user.getId()));
        return row > 0 ? JsonData.buildSuccess() : JsonData.buildError("删除失败");
    }

    @Override
    public JsonData goodTopic(Long topicId) {
        TopicDO topicDO = topicMapper.selectById(topicId);
        topicMapper.update(new UpdateWrapper<TopicDO>()
                .set("good",topicDO.getGood())
                .eq("id",topicId));
        return JsonData.buildSuccess();
    }


}
